package com.atcumt.community.controller;

import com.atcumt.community.service.AlphaService;
import com.atcumt.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/alpha")
public class HelloWorld {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello () {
        return "Hello, Spring Boot!";
    }

    // 处理查询请求
    @RequestMapping("/data")
    @ResponseBody
    public String getData () {
        return alphaService.find();
    }

    @RequestMapping("/http")
    public void http (HttpServletRequest request, HttpServletResponse response) {

        // 获取请求数据
        System.out.println(request.getMethod()); // GET
        System.out.println(request.getServletPath()); // /alpha/http
        System.out.println(request.getParameter("code")); // 返回 code值

        // 返回响应数据
        response.setContentType("text/html;charset=utf-8"); // 返回网页
        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write("<h1>牛客网</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // GET请求
    // /students?current=1&limit=20
    // @RequestParam 对 request的参数进行更详细的申明
    @RequestMapping(path = "/students", method = RequestMethod.GET)  // 限制请求 get方法
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    // 根据 id查学生, /student/666
    // @PathVariable 路径变量
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        System.out.println(id);
        return "a student";
    }

    // POST请求
    // 提交表单后，返回到控制台
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    // 响应HTML数据 (动态html)
    // 法一：ModelAndView 封装的 Model和视图给 DispatcherServlet调度
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher () {
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "陈新兴");
        mav.addObject("age", "46");
        mav.setViewName("/demo/view");  // 模板的路径和名字
        return mav;
    }

    // 法二：model数据装入参数中, view数据直接返回
    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        model.addAttribute("name", "中国矿业大学");
        model.addAttribute("age", 110);
        return "/demo/view";
    }

    // 响应 JSON数据 (异步请求：网页不刷新，访问服务器，举例：注册昵称)
    // Java对象 -> JSON字符串 -> JS对象
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        return emp;
    }

    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 24);
        emp.put("salary", 9000.00);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 25);
        emp.put("salary", 10000.00);
        list.add(emp);

        return list; // json字符串
    }

    // cookie示例：保存在客户端的一小块数据
    // 接受浏览器请求
    @RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        // 创建cookie,将其存到 response中，响应时自动携带给浏览器
        // 每个 cookie对象只能存储一对 key-value
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        // 设置cookie生效的范围
        cookie.setPath("/community/alpha");
        // 设置cookie的生存时间,存在硬盘中，默认存在内存中，关掉浏览器就消失
        cookie.setMaxAge(60 * 10);
        // 发送cookie，将cookie添加到response头中
        response.addCookie(cookie);

        return "set cookie successfully！";
    }

    // @CookieValue 浏览器取出cookie传给服务器
    @RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get cookie successfully！";
    }

    // session示例：JavaEE标准，保存在服务端，用于记录客户端信息

    @RequestMapping(path = "/session/set", method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session) {
        session.setAttribute("id", 1);
        session.setAttribute("name", "test");
        return "set session successfully！";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session successfully！";
    }

    // ajax示例
    // 页面不刷新，浏览器访问服务器获得数据
    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功!");
    }
}
